// var sockTask = require('../../app')
var timeUtil = require('../../utils/Time')
import TimeShow from '../../utils/TimeShow.js'
import { request } from '../../request/index.js'
//消息协议
var SocketMessage = require('../../utils/SocketMessage')
import getUserInfo from '../../utils/getUserInfo'

Page({
  data: {
    message: [],
    userId: null,
    chatId: null,
    isAnmation: false,
    lastId: 0,
    bottonid: '',
    // 用户输入内容
    mes: '',
    // 键盘高度
    keyHeight: 380,
    // 表情框显示
    isShow: false,
    // 页面是否上推
    pagTop: false,
    inputTop: false,
    // 表情
    emojis: [
      '😀',
      '😃',
      '😄',
      '😁',
      '😆',
      '😅',
      '🤣',
      '😂',
      '🙂',
      '🙃',
      '😉',
      '😊',
      '😇',
      '🥰',
      '😍',
      '🤩',
      '😘',
      '😗',
      '😚',
      '😙',
      '😋',
      '😛',
      '😜',
      '🤪',
      '😝',
      '🤑',
      '🤗',
      '🤭',
      '🤫',
      '🤔',
      '🤐',
      '🤨',
      '😐',
      '😑',
      '😶',
      '😏',
      '😒',
      '🙄',
      '😬',
      '🤥',
      '😌',
      '😔',
      '😪',
      '🤤',
      '😴',
      '😷',
      '🤒',
      '🤕',
      '🤢',
      '🤮',
      '🤧',
      '🥵',
      '🥶',
      '🥴',
      '😵',
      '🤯',
      '🤠',
      '🥳',
      '😎',
      '🤓',
      '🧐',
      '😕',
      '😟',
      '🙁',
      '☹️',
      '😮',
      '😯',
      '😲',
      '😳',
      '🥺',
      '😦',
      '😧',
      '😨',
      '😰',
      '😥',
      '😢',
      '😭',
      '😱',
      '😖',
      '😣',
      '😞',
      '😓',
      '😩',
      '😫',
      '🥱',
      '😤',
      '😡',
      '😠',
      '🤬'
    ]
  },

  uInfo: null,
  userInfo: null,

  async onMessage(data, isweidu) {
    if (isweidu) {
      let message = wx.getStorageSync('message')
      const { chatId } = this.data
      if (chatId == null) return
      message = message[chatId]
      if (message === '' || !message) {
        message = []
      } else {
        message.forEach((item, index) => {
          item['mid'] = index
        })
      }
      message = this.setTimes2(message)
      if (message.length != this.data.message.length) {
        this.setData(
          {
            message
          },
          () => {
            if (this.data.message.length > 0) this.setBott()
          }
        )
      }
      const { data } = await request({
        url: `/read0/${this.data.userId}/${this.data.chatId}`,
        dataType: 'json'
      })
      let message1 = wx.getStorageSync('message')
      let len = 0
      message1[this.data.chatId].forEach((item) => {
        if (item['isku']) {
          item['isku'] = false
          len += 1
        }
      })
      getApp().globalData.wdxx -= len
      wx.setStorageSync('message', message1)
    } else {
      if (data.messageType == 0) {
        if (data.userId == this.data.chatId) {
          const ids = [data.userId]
          const uInfo = await getUserInfo(ids)
          let { message, lastId } = this.data
          const mm = {
            mid: lastId + 1,
            id: 1,
            message: data.message,
            stime: data.stime,
            usernmae: uInfo[0].username,
            tou: uInfo[0].headpic
          }
          message.push(mm)
          message = this.setTimes2(message)
          if (this.data.isAnmation === false) {
            this.setData(
              {
                isAnmation: true
              },
              () => {
                this.setData({
                  message,
                  lastId: lastId + 1,
                  bottonid: `s${lastId + 1}`
                })
              }
            )
          } else {
            this.setData({
              message,
              lastId: lastId + 1,
              bottonid: `s${lastId + 1}`
            })
          }

          let userLie = wx.getStorageSync('userLie')
          userLie.forEach((element, index) => {
            if (element.chatId == data.userId) {
              getApp().globalData.wdxx -= userLie[index].weidu
              userLie[index].weidu = 0
            }
          })
          wx.setStorageSync('userLie', userLie)
        }
      }
    }
  },

  onLoad: async function (options) {
    this.userInfo = wx.getStorageSync('userInfo')
    // 显示最后一条消息
    const { chatId } = options
    const ufo = await getUserInfo([chatId])
    this.uInfo = ufo[0]
    // 显示聊天人名字
    wx.setNavigationBarTitle({
      title: this.uInfo.username
    })
    let userLie = wx.getStorageSync('userLie')
    let i = null
    if (!userLie) userLie = []
    userLie.forEach((element, index) => {
      if (element.chatId == chatId) {
        i = index
        getApp().globalData.wdxx -= userLie[index].weidu
        userLie[index].weidu = 0
      }
    })
    wx.setStorageSync('userLie', userLie)
    try {
      const uid = wx.getStorageSync('userId')
      const { data } = await request({
        url: `/read0/${uid}/${chatId}`,
        dataType: 'json'
      })
      console.log('返回已读', data)
      let message = wx.getStorageSync('message')
      message[chatId].forEach((item) => {
        if (item['isku']) item['isku'] = false
      })
      wx.setStorageSync('message', message)
    } catch (e) {
      console.log('返回已读错误', e)
    }

    this.setData(
      {
        userId: wx.getStorageSync('userId'),
        chatId
      },
      () => {
        let message = wx.getStorageSync('message')
        message = message[chatId]
        if (message === '' || !message) {
          message = []
        } else {
          message.forEach((item, index) => {
            item['mid'] = index
          })
        }
        message = this.setTimes2(message)
        this.setData(
          {
            message
          },
          () => {
            if (this.data.message.length > 0) this.setBott()
          }
        )
      }
    )
    // 获取键盘高度
    this.getKeyHeight()
  },

  onShow() {},

  onUnload() {
    // sockTask.SocketTask.close()
    wx.setStorageSync('status', 0)
  },

  // 获取最后一条消息显示
  setBott() {
    let { message } = this.data
    this.setData({
      bottonid: `s${message[message.length - 1].mid}`,
      lastId: message[message.length - 1].mid
    })
  },

  // 监听键盘高度变化
  getKeyHeight() {
    wx.onKeyboardHeightChange((res) => {
      let pagTop = false
      // let inputTop = false
      if (res.height !== 0 && this.data.keyHeight !== res.height) {
        this.setData({
          keyHeight: res.height
        })
      }
      if (res.height === 0 && this.data.isShow === false) {
          pagTop = false
      } else {
        pagTop = true
      }
      this.setData({
        pagTop
      })
    })
  },
  // 输入框值的变化
  changValue(e) {
    this.setData({
      mes: e.detail.value
    })
  },
  // 发送消息
  faSo() {
    if (this.data.mes === '') return

    const dataMes = {
      userId: this.data.userId,
      chatId: this.data.chatId,
      message: this.data.mes,
      messageType: SocketMessage.PRIVATE_CHAT,
      stime: timeUtil.formatTime(new Date())
    }
    wx.sendSocketMessage({
      data: JSON.stringify(dataMes),
      success: (res) => {
        // 判断
        let userLie = wx.getStorageSync('userLie')
        let i = null
        if (!userLie) userLie = []
        userLie.forEach((element, index) => {
          if (element.chatId == this.data.chatId) {
            i = index
          }
        })
        if (i == null) {
          userLie.unshift({
            chatId: this.data.chatId,
            name: this.uInfo.username,
            weidu: 0,
            time: TimeShow(timeUtil.formatTime(new Date())),
            lastmes: this.data.mes,
            lasttime: timeUtil.formatTime(new Date()),
            tou: this.uInfo.headpic,
            isTouchMove: false,
            isTop: false
          })
          wx.setStorageSync('userLie', userLie)
        } else {
          userLie[i].time = TimeShow(timeUtil.formatTime(new Date()))
          userLie[i].lastmes = this.data.mes
          userLie[i].lasttime = timeUtil.formatTime(new Date())
          wx.setStorageSync('userLie', userLie)
        }
      },
      fail: (err) => {
        console.log('失败')
      }
    })

    let { message, lastId } = this.data
    const mm = {
      mid: lastId + 1,
      id: 0,
      message: this.data.mes,
      stime: timeUtil.formatTime(new Date()),
      usernmae: this.userInfo.nickName,
      tou: this.userInfo.avatarUrl
    }
    message.push(mm)
    message = this.setTimes2(message)

    // 关闭键盘
    wx.hideKeyboard({
      success: (res) => {
        console.log('hideKeyboard res', res)
      }
    })
    if (this.data.isAnmation === false) {
      this.setData(
        {
          isAnmation: true
        },
        () => {
          this.setData({
            message,
            mes: '',
            lastId: lastId + 1,
            bottonid: `s${lastId + 1}`,
            isShow: false,
            pagTop: false
          })
        }
      )
    } else {
      this.setData({
        message,
        mes: '',
        lastId: lastId + 1,
        bottonid: `s${lastId + 1}`,
        isShow: false,
        pagTop: false
      })
    }
    let allMessage = wx.getStorageSync('message')
    if (!allMessage) allMessage = {}
    allMessage[this.data.chatId] = message
    wx.setStorageSync('message', allMessage)
  },
  // 点击表情框的显示与隐藏
  changeBiao() {
    this.setData(
      {
        isShow: !this.data.isShow
      },
      () => {
        if (this.data.isShow === false) {
          this.setData({
            pagTop: false
          })
        } else {
          this.setData({
            pagTop: true,
          })
        }
      }
    )
    // 关闭键盘
    wx.hideKeyboard({
      success: (res) => {
        console.log('hideKeyboard res', res)
      }
    })
  },
  closeInput() {
    this.setData({
      isShow: false,
      pagTop: false
    })
    // 关闭键盘
    wx.hideKeyboard({
      success: (res) => {
        console.log('hideKeyboard res', res)
      }
    })
  },
  // 点击input隐藏表情
  changeFalse() {
    this.setData({
      isShow: false
    })
  },
  // 用户选择表情
  chose(e) {
    const { emojis } = this.data
    const { index } = e.currentTarget.dataset
    this.setData({
      mes: `${this.data.mes}${emojis[index]}`
    })
  },

  // 消息时间距离
  setTimes() {
    // let { message } = this.data
    let message = wx.getStorageSync('message')

    message = this.setTimes2(message)
    this.setData({
      message
    })
  },
  // 带参
  setTimes2(message) {
    for (let i = 0; i < message.length; i++) {
      message[i]['time'] = TimeShow(message[i].stime)
      let biao = ' '
      if (i - 1 >= 0) {
        for (let a = i - 1; a >= 0; a--) {
          if (message[a]['time'] != '') {
            biao = message[a]['time']
            if (biao == message[i]['time']) {
              message[i]['time'] = ''
            }
          }
        }
      }
    }
    return message
  }
})
